/**
 * @author yxw
 * date : 2013年9月30日 下午3:43:33 
 */
package com.tzinfo.tzt.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.view.ImageAdapter;
import com.tzinfo.tzt.activity.view.XListView;
import com.tzinfo.tzt.activity.view.XListView.IXListViewListener;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.config.FilterConfig;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.NewhouseList;
import com.tzinfo.tzt.service.HouseHistoryService;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;

public class FilterNewHouseResultActivity extends BaseActivity implements
		IXListViewListener, OnClickListener, OnItemClickListener {

	private Button btnBack;
	private LinearLayout layoutConstraint;
	private TextView titleText, constraintText;

	private XListView xListView;

	private List<Map<String, Object>> data;
	private List<Object> houseList;
	private Handler mHandler;
	// 筛选相关
	private int[] filterResult;
	private int tabNum = 0;
	private StringBuilder filterStr = new StringBuilder("?listtype=1");
	private String baseUrl = AppDataConfig.xinfangUrl
			+ AppDataConfig.NewhouseList;


	private ImageAdapter imageAdapter;
	private HouseHistoryService historyService;
	// 标志
	private int attrType = 0;

	private MyResultList newHouseListResult;

	static String sImg = "img";
	static String sTitle = "title";
	static String sAdress = "adress";
	static String sSize = "size";
	static String sPrice = "price";
	static String sHouseId = "houseId";
	static String sAttr = "attr";
	private int pageNum = 1;
	private static final int pageSize = 10;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_filter_house);
		createfilterStr();
		init();
		historyService=new HouseHistoryService(this);
		showProgressBar();
		new Thread(getNewHouseListResultRun).start();
	}

	private void createfilterStr() {
		Intent thisIntent = this.getIntent();
		filterResult = thisIntent.getIntArrayExtra("filterResult");
		tabNum = thisIntent.getIntExtra("tabNum", 0);

		filterStr.append("&areaid=" + filterResult[0]);
		String price = FilterConfig.FILTER_PRICE_Y[filterResult[1]];
		if (filterResult[1] == 0) {
			// filterStr.append("&money= ");
		} else if (filterResult[1] == 1) {
			filterStr.append("&money=0-0");
		} else if (filterResult[1] == FilterConfig.FILTER_PRICE_Y.length - 1) {
			price = price.substring(0, price.length() - 3) + "-";
			filterStr.append("&money=" + price);
		} else {
			price = price.substring(0, price.length() - 1);
			filterStr.append("&money=" + price);
		}
		
		switch (tabNum) {
		case 1:
			baseUrl = AppDataConfig.xinfangUrl + AppDataConfig.NewhouseList;
			filterStr.append("&attr=3");
			break;
		case 2:
			baseUrl = AppDataConfig.oldUrl + AppDataConfig.OldhouseList;
			break;
		case 3:
			baseUrl = AppDataConfig.zufangUrl + AppDataConfig.RenthouseList;
			break;
		default:
			baseUrl = AppDataConfig.xinfangUrl + AppDataConfig.NewhouseList;
			break;
		}
	}

	private void init() {
		mHandler = new Handler();
		mProgressBar = (ProgressBar)findViewById(R.id.progressbar_loding);
		xListView = (XListView) findViewById(R.id.xListView_local);
		xListView.setPullRefreshEnable(false);
		xListView.setPullLoadEnable(true);
		// xListView.setPullLoadEnable(false);
		// xListView.setPullRefreshEnable(false);
		xListView.setXListViewListener(this);
		xListView.setOnItemClickListener(this);
		constraintText = (TextView) this.findViewById(R.id.text_constraint);
		String t = "找房条件：";
		for (int i = 0; i < filterResult.length; i++) {
			if (filterResult[i] != 0) {
				t += FilterConfig.FILTER_CONTENT[i][filterResult[i]] + " | ";
			}
		}
		if(t.length()!=5){
			t=t.substring(0, t.length()-3);
		}else{
			t="您没有设置找房条件";
		}
		constraintText.setText(t);
		titleText = (TextView) this.findViewById(R.id.text_title);
		titleText.setText("新房");

		btnBack = (Button) this.findViewById(R.id.bt_back);
		btnBack.setOnClickListener(this);
		layoutConstraint = (LinearLayout) this
				.findViewById(R.id.layout_constraint);
		layoutConstraint.setOnClickListener(this);
	}

	private void newAdapter() {
		// 自定义的图片适配器
		imageAdapter = new ImageAdapter(this, data, R.layout.item_main_list,
				new String[] { sImg, sTitle, sAdress, sSize, sPrice, sAttr,
						sHouseId }, new int[] { R.id.list_item_image,
						R.id.list_item_title, R.id.list_item_address,
						R.id.list_item_size, R.id.list_item_price,
						R.id.img_attr, R.id.un_house_id });
	}

	private void updateUI() {
		newAdapter();
		// xListView.setAdapter(simpleAdapter);
		xListView.setAdapter(imageAdapter);
	}

	/**
	 * 将得到的数据装载进ArrayList<Map<String, Object>>() data中
	 */
	private void getData() {
		data = new ArrayList<Map<String, Object>>();
		NewhouseList newhouseListItem;
		Map<String, Object> map;
		if (newHouseListResult.getSuccess()) {
			houseList=newHouseListResult.getData();
			for (int i = 0; i < newHouseListResult.getData().size(); i++) {
				newhouseListItem = (NewhouseList) newHouseListResult.getData()
						.get(i);
				map = new HashMap<String, Object>();
				map.put(sImg, newhouseListItem.getLogo());
				String strName = newhouseListItem.getName();
				if (strName.length() > 8) {
					strName = strName.substring(0, 8) + "…";
				}
				map.put(sTitle, strName);
				String strAdress = newhouseListItem.getAddress();
				if (strAdress.length() > 20) {
					strAdress = strAdress.substring(0, 20) + "…";
				}
				map.put(sAdress, strAdress);
				map.put(sSize, newhouseListItem.getStatus());
				String price = newhouseListItem.getPrice() + "";
				if (newhouseListItem.getPrice() == 0) {
					price = "售价待定";
				} else {
					price += "元/" + newhouseListItem.getPriceUnit();
				}
				map.put(sPrice, price);
				int attrId = R.drawable.transparent;
				switch (attrType = newhouseListItem.getAttr()) {
				case 1:
					attrId = R.drawable.tuan;
					break;
				case 2:
					attrId = R.drawable.kan;
					break;
				case 3:
					attrId = R.drawable.fang;
					break;
				}
				map.put(sAttr, attrId);
				map.put(sHouseId, newhouseListItem.getId() + "&&" + attrType);
				data.add(map);
			}
		}
	}

	private void getMoreData() {
		NewhouseList newhouseListItem;
		Map<String, Object> map;
		if (newHouseListResult.getSuccess()) {

			for (int i = 0; i < newHouseListResult.getData().size(); i++) {
				houseList.add(newHouseListResult.getData().get(i));
				newhouseListItem = (NewhouseList) newHouseListResult.getData()
						.get(i);
				map = new HashMap<String, Object>();
				map.put(sImg, newhouseListItem.getLogo());
				String strName = newhouseListItem.getName();
				if (strName.length() > 9) {
					strName = strName.substring(0, 9) + "…";
				}
				map.put(sTitle, strName);
				String strAdress = newhouseListItem.getAddress();
				if (strAdress.length() > 20) {
					strAdress = strAdress.substring(0, 20) + "…";
				}
				map.put(sAdress, strAdress);
				map.put(sSize, newhouseListItem.getStatus());
				String price = newhouseListItem.getPrice() + "";
				if (newhouseListItem.getPrice() == 0) {
					price = "售价待定";
				} else {
					price += "元/" + newhouseListItem.getPriceUnit();
				}
				map.put(sPrice, price);
				int attrId = R.drawable.transparent;
				switch (attrType = newhouseListItem.getAttr()) {
				case 1:
					attrId = R.drawable.tuan;
					break;
				case 2:
					attrId = R.drawable.kan;
					break;
				case 3:
					attrId = R.drawable.fang;
					break;
				}
				map.put(sAttr, attrId);
				map.put(sHouseId, newhouseListItem.getId() + "&&" + attrType);
				data.add(map);
			}
		}
	}

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						showProgressBar();
						new Thread(getMoreNewHouseListResultRun).start();
					}
				}).show();
	}

	protected void showLastRow() {
		Toast.makeText(this, "已经是最后一页！", 5000).show();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case -1:
				getDataError((String) msg.obj);
				break;
			case 1:
				updateUI();
				if (xListView.getFooterViewsCount() == 0) {
					xListView.addFooterView(xListView.getmFooterView());
				}
				removeProgressBar();
				onLoad();
				break;
			case 2:
				if (xListView.getFooterViewsCount() == 0) {
					xListView.addFooterView(xListView.getmFooterView());
				}
				imageAdapter.notifyDataSetChanged();
				onLoad();
				break;
			case 3:
				// 最后一页
				showLastRow();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				onLoad();
				break;
			case 4:
				// 没有数据
				updateUI();
				data.clear();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				imageAdapter.notifyDataSetChanged();
				// xListView.setVisibility(View.GONE);
				removeProgressBar();
				onLoad();
				break;
			case 5:
				// 只有一页
				updateUI();
				onLoad();
				if (xListView.getFooterViewsCount() > 0) {
					xListView.removeFooterView(xListView.getmFooterView());
				}
				removeProgressBar();
				break;
			case 0:
				break;
			}
		}
	};

	private void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		xListView.setRefreshTime(df.format(new Date()));
	}

	private void initData() {
		pageNum = 1;
		// 通过线程访问网络得到数据
		new Thread(getNewHouseListResultRun).start();
	}

	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				// getData();
				// 如果刷新后数据不变，会出错
				// simpleAdapter.notifyDataSetChanged();
				// newAdapter();
				// xListView.setAdapter(simpleAdapter);
				pageNum = 1;
				initData();

			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				pageNum++;
				new Thread(getMoreNewHouseListResultRun).start();

			}
		}, 2000);
	}

	/**
	 * 线程 得到新房列表
	 */
	Runnable getNewHouseListResultRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String sFilter = filterStr.toString() + "&pagenumber=" + pageNum
					+ "&pagesize=" + pageSize;
			Log.wtf("url", baseUrl + sFilter);
			jsonString = HttpTools.getJsonContent(baseUrl + sFilter, "GB2312");
			Log.e("JsonString", jsonString);
			newHouseListResult = JsonTools.getNewhouseList(jsonString);
			getData();
			if (newHouseListResult.getSuccess()) {
				if (newHouseListResult.getData().size() == 0) {
					msg.arg1 = 4;
				} else if (newHouseListResult.getData().size() < pageSize) {
					msg.arg1 = 5;
				} else {
					msg.arg1 = 1;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = newHouseListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};
	/**
	 * 线程 得到新房列表
	 */
	Runnable getMoreNewHouseListResultRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String sFilter = filterStr.toString() + "&pagenumber=" + pageNum
					+ "&pagesize=" + pageSize;
			jsonString = HttpTools.getJsonContent(baseUrl + sFilter, "GB2312");
			Log.e("JsonString gb2312", jsonString);
			newHouseListResult = JsonTools.getNewhouseList(jsonString);
			getMoreData();
			if (newHouseListResult.getSuccess()) {
				if (newHouseListResult.getData().size() == 0) {
					msg.arg1 = 3;
				} else {
					msg.arg1 = 2;
				}
			} else {
				msg.arg1 = -1;
				msg.obj = newHouseListResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			finish();
			break;
		case R.id.layout_constraint:
			// 跳转到定位条件选择页面
			this.finish();
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(FilterNewHouseResultActivity.this,
				NewHouseDetailActivity.class);
		NewhouseList item = (NewhouseList) houseList.get((int) arg3);
		TextView text = (TextView) arg1.findViewById(R.id.un_house_id);
		intent.putExtra(sHouseId, text.getText().toString());
		intent.putExtra("newhouseList", item);
		historyService.saveNewHouse(item);
		
		startActivity(intent);

	}

}
